const http = require("http");
const fs = require("fs");
const path = require("path");
const mime = require("mime");
const _ = require("underscore");

const rootname = path.join(__dirname,"www");

http.createServer().on("request",(req,res)=>{
    req.url = decodeURI(req.url);
    let name = path.join(rootname,req.url);
    if(fs.existsSync(name)){
        //文件存在
        fs.stat(name,(err,stats)=>{
            if(err){

            }else{
                if(stats.isDirectory()){
                    //文件夹
                   fs.readdir(name,(err,files)=>{
                        if(err){

                        }else{
                            fs.readFile(path.join(__dirname,"view/list.html"),"utf-8",(err,data)=>{
                                if(err){
        
                                }else{
                                    let html = _.template(data)({files,url:req.url});
                                    res.end(html);
                                }
                            })
                        }
                   })
                }else{
                    //文件
                    fs.readFile(name,(err,data)=>{
                        if(err){
                            
                        }else{
                            res.setHeader("Content-Type",mime.getType(name));
                            res.end(data);
                        }
                    })
                }
            }
        })

    }else{
        //文件不存在
        res.statusCode = 404;
        res.statusMessage = "NotFound";
        res.end();
    }


}).listen(80,()=>console.log("服务器启动成功"));